<?php

namespace app\api\controller\wechat;
use think\Db;
use think\Controller;
class Home extends Controller
{



    //获取banner图
    public function banner(){
        $post = input('post.');
        $page_type = isset($post['page_type']) && $post['page_type'] != '' ? $post['page_type'] : 0;
        $res=db('banner')->where(['status'=>0,'is_delete'=>0,'page_type'=>$page_type])->select();
        return json(array('code' => '1', 'msg' => '请求成功','data'=>$res));
    }

    //获取城市列表
    public function city(){
        $res=db('city')->where(['status'=>0,'is_delete'=>0])->select();
        return json(array('code' => '1', 'msg' => '请求成功','data'=>$res));
    }

    //获取店铺列表 crm_store
    public function store(){
        if (request()->isPost()) {
            $post = input('post.');
            $lat = isset($post['lat']) && $post['lat'] != '' ? $post['lat'] : null;
            $lng = isset($post['lng']) && $post['lng'] != '' ? $post['lng'] : null;
            if(!$lat){
                return json(array('code' => '1', 'msg' => '成功','data'=>null));
            }
            $list = db('store')
                ->alias('xf')
                ->field('xf.*,s.title as city_title')
                ->join('city s','s.id=xf.city_id','left')
                ->where(['xf.status'=>0,'xf.is_delete'=>0])
                ->select();
            foreach ($list as &$v){
                $v['distance']=$this->getDistance($lat,$lng,$v['lat'],$v['lng']);
            }
            $sortList=$this->sortArr($list,'distance');
            $data=count($sortList)>0?$sortList[0]:null;
            return json(array('code' => '1', 'msg' => '请求成功','data'=>$data));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     *
     * @return \think\response\Json|void
     *  comppub
     *
     */

    public function storeList(){
        $page = $this->request->param('pageIndex');
        $keyword = $this->request->param('title');
        $city = $this->request->param('city');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and s.is_delete=0";
        if (!empty($keyword)) {
            $param.=" and s.title like '%$keyword%' ";
        }
        if(!empty($city)){
            $param.=" and s.city_id=$city ";
        }
        $sql2="select s.*,c.title as city_name from crm_store as s ";
        $sql2.="left join crm_city as c on c.id=s.city_id";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by s.sort desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1);
        if($lat && $lng){
            foreach ($list as &$v){
                $v['distance']=$this->getDistance($lat,$lng,$v['lat'],$v['lng']);
            }
            $list=$this->sortArr($list,'distance');
        }
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    public function sortArr($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
        $key_arrays =array();
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }


    public function getDistance($lat1, $lng1, $lat2, $lng2){

        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }


    public function getCategoryList(){
        $page_type = $this->request->param('page_type');
        $parent=db('server_cate')->where(['is_delete'=>0,'parent_id'=>0,'page_type'=>$page_type])->order('sort desc')->select();
        $list=db('server_cate')->where(['is_delete'=>0,'parent_id'=>array('gt',0)])->select();
        foreach ($parent as &$v){
            $v['children']=[];
            foreach ($list as &$vv){
                if($vv['parent_id']==$v['id']){
                    $v['children'][]=$vv;
                }
            }
        }
        return json(['code'=>1,'msg'=>'success','data'=>$parent]);
    }


    public function getServerList(){
        $page = $this->request->param('pageIndex');
        $keyword = $this->request->param('title');
        $cate = $this->request->param('cate');
        $type = $this->request->param('type');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and s.is_delete=0 ";
        if (!empty($keyword)) {
            $param.=" and s.name like '%$keyword%' ";
        }
        if(!empty($cate)){
            $cRes=db('server_cate')->where(['is_delete'=>0,'id'=>$cate])->find();
            if($cRes){
                if($cRes['parent_id'] == 0){
                    $param.=" and (s.cate_id in (select id from crm_server_cate where parent_id=$cate) or s.cate_id=".$cate.")";
                }else{
                    $param.=" and s.cate_id=$cate ";
                }
            }else{
                $param.=" and s.cate_id=$cate ";
            }

        }
        $sql2="select s.*,c.title as cate_name from crm_server as s ";
        $sql2.="left join crm_server_cate as c on c.id=s.cate_id";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by s.sort desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    public function getSubscribe(){
        $res=db('subscribe_config')->where(['is_delete'=>0,'status'=>0])->find();
        return json(['code'=>1,'msg'=>'操作成功','data'=>$res]);
    }

    public function getAppointInfoByDate(){
        $store_id = $this->request->param('store_id');
        $appoint_date = $this->request->param('appoint_date');
        if(!$appoint_date){
            return json(['code'=>0,'msg'=>'预约日期错误']);
        }
        $res=db('subscribe_config')->where(['is_delete'=>0,'status'=>0])->find();
        $time1 = $res && $res['start_time']?$res['start_time']:'08:30';
        $time2 = $res && $res['end_time']?$res['end_time']:'18:30';
        $interval=$res && $res['interval']?$res['interval']:30;
        $buff = array();
        for($i=strtotime($appoint_date.' '.$time1) ;$i<=strtotime($appoint_date.' '.$time2) ; $i=$i+60*$interval){
            $buff[]=array(
                'time'=>date("H:i",$i),
                'status'=>$i<time()?0:1
            );
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>$buff]);
    }


    public function getAppointUser(){
        $appoint_date = $this->request->param('appoint_date');
        $open_id = $this->request->param('open_id');
        $isLogin=$this->isLogin($open_id);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        if(!$appoint_date){
            return json(['code'=>0,'msg'=>'预约日期错误']);
        }
        $appoint=strtotime($appoint_date);
        $res=db('user_order')->where(['status'=>1,'member_id'=>$isLogin['id'],'subscribe_time'=>$appoint])->find();
        return json(['code'=>1,'msg'=>'操作成功','data'=>$res?0:1]);
    }

    public function getStoreDetail(){
        $id = $this->request->param('store_id');
        $lat=$this->request->param('lat');
        $lng=$this->request->param('lng');
        $res=db('store')->where(['id'=>$id,'status'=>0])->find();
        if($res){
            $res['distance']=$this->getDistance($lat,$lng,$res['lat'],$res['lng']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>$res]);
    }



    public function isLogin($openid){
        $res=db('member_user')->where(['openid'=>$openid])->find();
        return ($res && $res['mobile'])?$res:false;
    }


    //保存会员信息
    public function setUserInfo(){
        if (request()->isPost()) {
            $post = input('post.');
            $mobile = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : 0;
            if(!$mobile){
                return json(array('code' => '0', 'msg' => '手机号码错误'));
            }
            $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
            $avatarUrl = isset($post['avatarUrl']) && $post['avatarUrl'] != '' ? $post['avatarUrl'] : null;
            $nickName = isset($post['nickName']) && $post['nickName'] != '' ? $post['nickName'] : null;
            $user=db('member_user')->where(['mobile'=>$mobile])->find();
            $member_id=null;
            if(!$user){
                $open=db('member_user')->where(['openid'=>$openid])->find();
                if($open){
                    $member_id=$open['id'];
                }
            }else{
                $member_id=$user['id'];
            }
            $data['headimgurl']=$avatarUrl;
            $data['wechat_nickname']=$nickName;
            $data['update_time']=time();
            $data['openid']=$openid;
            $data['mobile']=$mobile;
            if($member_id){
                $res=db('member_user')->where(['id'=>$member_id])->update($data);
                if(!$res){
                    return json(array('code' => '0', 'msg' => '用户信息失败'));
                }
            }else{
                $data['create_time']=time();
                $res=db('member_user')->insert($data);
                if(!$res){
                    return json(array('code' => '0', 'msg' => '用户信息失败'));
                }
            }
            return json(array('code' => '1', 'msg' => '请求成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //获取会员信息
    public function getUserInfo(){
        if (request()->isPost()) {
            $post = input('post.');
            $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
            $isLogin=$this->isLogin($openid);
            if($isLogin === false){
                return json(['code'=>-1,'msg'=>'未登录请先登录']);
            }
            $isLogin['is_technician']=false;
            $res=db('technician')->where(['mobile'=>$isLogin['mobile'],'is_delete'=>0,'status'=>0])->find();
            $czTotal=db('member_integral')->where(['member_id'=>$isLogin['id'],'integral_type'=>1])->sum('integral_num');
            $xfTotal=db('member_integral')->where(['member_id'=>$isLogin['id'],'integral_type'=>2])->sum('integral_num');
            if($res){
                $isLogin['is_technician']=$res['is_technician']==1?1:2;
                $integralTotal=$czTotal-$xfTotal;
                $isLogin['integral_total']=$integralTotal;
            }
            return json(array('code' => '1', 'msg' => '请求成功','data'=>$isLogin));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //保存会员信息
    public function getUserDetail(){
        if (request()->isPost()) {
            $post = input('post.');
            $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
            $res=db('crm_member_user')->where(['openid'=>$openid])->find();
            if($res && $res['mobile']){
                return json(array('code' => '1', 'msg' => '请求成功','data'=>$res));
            }else{
                return json(array('code' => '-1', 'msg' => '请求成功','data'=>$res));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //会员卡信息
    public function accountCards(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $res=db('member_vip')->where(['member_id'=>$isLogin['id']])->find();
        if($res){
            $res['card_info']=db('cards')->where(['id'=>$res['card_id']])->find();
            $res['record_num']=db('member_record')->where(['is_delete'=>0,'member_id'=>$isLogin['id'],'record_type'=>1,'katz_or_amount'=>1])->count('id');
            $res['card_status']=$res['card_end_time']<time()?false:true;
            $res['user']=$isLogin;
        }
        return json(array('code' => '1', 'msg' => '请求成功','data'=>$res));
    }


    public function getAppointRecords(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $page = $this->request->param('pageIndex');
        $mobile = $this->request->param('mobile');
        $name = $this->request->param('name');
        $store_id = $this->request->param('store_id');
        $status = $this->request->param('status');
        $technician_id = $this->request->param('technician_id');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and o.is_delete=0 and o.member_id=".$isLogin['id'];
        if (!empty($mobile)) {
            $param.=" and o.member_id in (select id from crm_member_user where mobile like '%$mobile%' and is_delete=0) ";
        }
        if (!empty($name)) {
            $param.=" and o.member_id in (select id from crm_member_user where nickname like '%$name%' and is_delete=0) ";
        }
        if (!empty($store_id)) {
            $param.=" and o.store_id=".$store_id;
        }
        if (!empty($store_id)) {
            $param.=" and o.technician_id=".$technician_id;
        }
        if (!empty($status)) {
            $param.=" and o.status in (".$status.")";
        }
        $sql2="SELECT o.*,s.title as store_title,s.address as store_address,s.lat as store_lat,s.lng as store_lng,s.tel as store_tel,c.name as server_name,c.price as server_price,t.name as technician_name,q.monetary,q.record_type,q.katz_or_amount,u.nickname,u.mobile FROM crm_user_order AS o ";
        $sql2.=" LEFT JOIN crm_store AS s ON s.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS c ON c.id=o.server_id ";
        $sql2.=" LEFT JOIN crm_technician AS t ON t.id=o.technician_id ";
        $sql2.=" LEFT JOIN crm_member_record AS q ON q.order_id=o.id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=o.member_id ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by o.id desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    public function getAppointRecordsDetail(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $id = $this->request->param('id');
        $param=" and o.id=".$id;
        $sql2="SELECT o.*,s.title as store_title,s.address as store_address,s.lat as store_lat,s.lng as store_lng,s.tel as store_tel,c.name as server_name,c.price as server_price,t.name as technician_name,q.monetary,q.record_type,q.katz_or_amount,u.nickname,u.mobile FROM crm_user_order AS o ";
        $sql2.=" LEFT JOIN crm_store AS s ON s.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS c ON c.id=o.server_id ";
        $sql2.=" LEFT JOIN crm_technician AS t ON t.id=o.technician_id ";
        $sql2.=" LEFT JOIN crm_member_record AS q ON q.order_id=o.id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=o.member_id ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        foreach ($list as &$v){
            $v['order_xh_img']=db('user_order_img')->where(['order_id'=>$v['id']])->select();
        }
        return json(['code'=>1,'msg'=>'success','data'=>count($list)>0?$list[0]:null]);
    }


    //保存会员信息
    public function submitOrder(){
        if (request()->isPost()) {
            $post = input('post.');
            $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
            if(!$openid){
                return json(array('code' => '0', 'msg' => '用户信息错误'));
            }
            $isLogin=$this->isLogin($openid);
            if($isLogin === false){
                return json(['code'=>-1,'msg'=>'未登录请先登录']);
            }
            $subscribe_time = isset($post['subscribe_time']) && $post['subscribe_time'] != '' ? $post['subscribe_time'] : null;
            if(!$subscribe_time){
                return json(array('code' => '0', 'msg' => '预约时间错误'));
            }
            $store_id = isset($post['store_id']) && $post['store_id'] != '' ? $post['store_id'] : 0;
            $sRes=db('store')->where(['is_delete'=>0,'status'=>0,'id'=>$store_id])->find();
            if(!$sRes){
                return json(array('code' => '0', 'msg' => '门店信息错误'));
            }
            $server_id = isset($post['server_id']) && $post['server_id'] != '' ? $post['server_id'] : 0;
            $vRes=db('server')->where(['is_delete'=>0,'status'=>0,'id'=>$server_id])->find();
            if(!$vRes){
                return json(array('code' => '0', 'msg' => '服务信息错误'));
            }
            $remarks = isset($post['remarks']) && $post['remarks'] != '' ? $post['remarks'] : null;

            $data['order_num']=date('YmdHis').rand(1000,9999);
            $data['create_time']=time();
            $data['update_time']=time();
            $data['member_id']=$isLogin['id'];
            $data['subscribe_time']=strtotime($subscribe_time);
            $data['store_id']=$store_id;
            $data['server_id']=$server_id;
            $data['remarks']=$remarks;
            $data['openid']=$openid;
            $data['status']=1;
            $oRes=db('user_order')->where(['subscribe_time'=>$data['subscribe_time'],'store_id'=>$store_id,'server_id'=>$server_id])->find();
            if($oRes){
                return json(array('code' => '0', 'msg' => '您已有预约订单,不可重复预约！'));
            }
            $r=db('user_order')->insert($data);
            if(!$r){
                return json(array('code' => '0', 'msg' => '操作失败！'));
            }
            return json(array('code' => '1', 'msg' => '操作成功！'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function serverDetail(){
        $server_id = $this->request->param('server_id');;
        $vRes=db('server')->where(['is_delete'=>0,'status'=>0,'id'=>$server_id])->find();
        return json(array('code' => '1', 'msg' => '操作成功！','data'=>$vRes));
    }


    public function queryConsumList(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $page = $this->request->param('pageIndex');
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $store_id = $this->request->param('store_id');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and x.is_delete=0 and x.member_id=".$isLogin['id'];
        if (!empty($name)) {
            $param.=" and x.member_id in (select id form crm_member_user where nickname like '%$name%') ";
        }

        if (!empty($mobile)) {
            $param.=" and x.member_id in (select id form crm_member_user where mobile like '%$mobile%') ";
        }

        if (!empty($store_id)) {
            $param.=" and x.order_id in (select id form crm_user_order where store_id=".$store_id.") ";
        }

        $sql2="select x.*,o.order_num,s.name as server_name,u.nickname,u.mobile,m.title as store_title from crm_member_record as x ";
        $sql2.=" LEFT JOIN crm_user_order AS o ON o.id=x.order_id ";
        $sql2.=" LEFT JOIN crm_store AS m ON m.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS s ON s.id=x.server_id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=x.member_id ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by s.id desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    //保存会员信息
    public function submitFeedback(){
        if (request()->isPost()) {
            $post = input('post.');
            $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
            if(!$openid){
                return json(array('code' => '0', 'msg' => '用户信息错误'));
            }
            $isLogin=$this->isLogin($openid);
            if($isLogin === false){
                return json(['code'=>-1,'msg'=>'未登录请先登录']);
            }
            $content = isset($post['content']) && $post['content'] != '' ? $post['content'] : null;
            $data['create_time']=time();
            $data['update_time']=time();
            $data['member_id']=$isLogin['id'];
            $data['content']=$content;
            $r=db('feedback')->insert($data);
            if(!$r){
                return json(array('code' => '0', 'msg' => '操作失败！'));
            }
            return json(array('code' => '1', 'msg' => '操作成功！'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function listRecharge(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $where['xf.member_id'] = $isLogin['id'];
        $list = Db::name('member_serve')
            ->alias('xf')
            ->field('xf.id as xf_id,xf.create_time as xf_create_time,s.*')
            ->join('cards_server s','s.id=xf.serve_id','left')
            ->where($where)
            ->order('xf.create_time desc')
            ->select();
        $recharge=db('member_recharge')->where(['member_id'=>$isLogin['id']])->select();
        $vList = Db::name('member_vip')
            ->alias('xf')
            ->field('xf.id as xf_id,xf.create_time as xf_create_time,s.*')
            ->join('cards s','s.id=xf.card_id','left')
            ->where($where)
            ->select();
        return json(array('code' => '1', 'msg' => '成功','serve'=>$list,'recharge'=>$recharge,'vip'=>$vList));
    }

    public function getUserRecord(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }

        $amount=db('member_recharge')->where(['is_delete'=>0,'member_id'=>$isLogin['id']])->sum('amount');
        $amountNum=db('member_record')->where(['is_delete'=>0,'member_id'=>$isLogin['id'],'record_type'=>2,'katz_or_amount'=>2])->sum('monetary');
        return json(array('code' => '1', 'msg' => '成功','amount'=>$amount-$amountNum,'wash_protect_num_total'=>$isLogin['wash_protect_num_total']));
    }


    public function integralList(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }

        $param=" and r.member_id=".$isLogin['id'];
        $sql2="SELECT r.* FROM crm_member_integral AS r ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        $czIntegral=[];$xfIntegral=[];
        foreach ($list as &$v){
            $v['create_time']=date('Y-m-s h:i:s',$v['create_time']);
            if($v['integral_type'] == 1){
                $czIntegral[]=$v;
            }else{
                $xfIntegral[]=$v;
            }

        }
        return json(['code'=>1,'msg'=>'success','data'=>['xfIntegral'=>$xfIntegral,'czIntegral'=>$czIntegral]]);
    }


    public function getTechnicianList(){
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $jsRes=db('technician')->where(['is_delete'=>0,'status'=>0,'mobile'=>$isLogin['mobile']])->find();
        $page = $this->request->param('pageIndex');
        $status = $this->request->param('status');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and o.is_delete=0 and o.technician_id=".($jsRes?$jsRes['id']:0);
        if (!empty($status)) {
            $param=" and o.status in (".$status.")";
        }
        $sql2="SELECT o.*,s.title as store_title,s.address as store_address,s.lat as store_lat,s.lng as store_lng,s.tel as store_tel,c.name as server_name,c.price as server_price,t.name as technician_name,q.monetary,q.record_type,q.katz_or_amount,u.nickname,u.wechat_nickname,u.mobile FROM crm_user_order AS o ";
        $sql2.=" LEFT JOIN crm_store AS s ON s.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS c ON c.id=o.server_id ";
        $sql2.=" LEFT JOIN crm_technician AS t ON t.id=o.technician_id ";
        $sql2.=" LEFT JOIN crm_member_record AS q ON q.order_id=o.id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=o.member_id ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by o.id desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    public function changeStatus()
    {
        $post = input('post.');
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $jsRes=db('technician')->where(['is_delete'=>0,'status'=>0,'mobile'=>$isLogin['mobile']])->find();
        if(!$jsRes){
            return json(['code' => 0, 'msg' => '技师信息错误']);
        }
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        if($oRes['technician_id']!=$jsRes['id']){
            return json(['code' => 0, 'msg' => '订单技师信息错误']);
        }
        $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
        $where['id'] = $order_id;
        $data['status'] = $status;
        $data['update_time'] = time();
        $r=db('user_order')->where($where)->update($data);
        if(!$r){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }


    public function chanelStatus()
    {
        $post = input('post.');
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $where['id'] = $order_id;
        $data['status'] = 6;
        $data['update_time'] = time();
        $r=db('user_order')->where($where)->update($data);
        if(!$r){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function writeOff(){
        $post = input('post.');
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $jsRes=db('technician')->where(['is_delete'=>0,'status'=>0,'mobile'=>$isLogin['mobile']])->find();
        if(!$jsRes){
            return json(['code' => 0, 'msg' => '技师信息错误']);
        }
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $img_type = isset($post['imgType']) && $post['imgType'] != '' ? $post['imgType'] : 0;
        if(!$img_type){
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        if($oRes['technician_id']!=$jsRes['id']){
            return json(['code' => 0, 'msg' => '订单技师信息错误']);
        }
        $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
        $write_off_img = isset($post['write_off_img']) && $post['write_off_img'] != '' ? $post['write_off_img'] : array();
        $list=explode(",", $write_off_img);
        if(is_array($list) && count($list)>0){
            $data=array();
            foreach ($list as &$v){
                $data[] = array(
                    'create_time'=>time(),
                    'order_id'=>$order_id,
                    'type'=>$img_type,
                    'url'=>$v
                );
            }
            if(count($list)>0){
                $r=db('user_order_img')->insertAll($data);
                if(!$r){
                    return json(['code' => 0, 'msg' => '操作失败']);
                }
                return json(['code' => 1, 'msg' => '操作成功']);
            }
        }else{
            return json(['code'=>-1,'msg'=>'图片信息错误']);
        }

    }

    public function storeDetail(){
        $id = $this->request->param('store_id');
        $lat=$this->request->param('lat');
        $lng=$this->request->param('lng');
        $res=db('store')->where(['id'=>$id,'status'=>0])->find();
        if($res){
            $res['distance']=$this->getDistance($lat,$lng,$res['lat'],$res['lng']);
        }
        return json(['code'=>1,'msg'=>'操作成功','data'=>$res]);
    }


    public function setUserInfos(){
        $post = input('post.');
        $openid = $this->request->param('openid');
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $mobile = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : 0;
        if(!$mobile){
            return json(array('code' => '0', 'msg' => '手机号码错误'));
        }
        $nickName = isset($post['nickName']) && $post['nickName'] != '' ? $post['nickName'] : null;
        if(!$nickName){
            return json(array('code' => '0', 'msg' => '用户姓名错误'));
        }
        $birthday = isset($post['birthDay']) && $post['birthDay'] != '' ? $post['birthDay'] : null;
        $address = isset($post['address']) && $post['address'] != '' ? $post['address'] : null;
        $unionid = isset($post['unionid']) && $post['unionid'] != '' ? $post['unionid'] : null;
        $data['mobile']=$mobile;
        $data['nickname']=$nickName;
        $data['update_time']=time();
        if($birthday){
            $data['birthday']=strtotime($birthday);
        }
        $data['address']=$address;
        $data['unionid']=$unionid;
        $r=db('member_user')->where(['id'=>$isLogin['id']])->update($data);
        if(!$r){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function config()
    {
        $result=db('config')->where(['id'=>1])->find();
        return json(array('code' => '1', 'msg' => '成功','data'=>$result));
    }

    /**
     *
     * @return \think\response\Json|void
     *  comppub
     *
     */

    public function articleList(){
        $page = $this->request->param('pageIndex');
        $keyword = $this->request->param('title');
        $recommend_type = $this->request->param('recommend_type');
        $recommend_type=$recommend_type?$recommend_type:0;
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and s.is_delete=0 and s.status=0 and  recommend_type=".$recommend_type;
        if (!empty($keyword)) {
            $param.=" and s.title like '%$keyword%' ";
        }
        $sql2="select s.* from crm_article as s ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by s.sort desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }

    /**
     * 基本信息修改
     * @return \think\response\Json|void
     */
    public function articleDetail()
    {
        $id = $this->request->param('id');


        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        $where['id'] = $id;
        $r=db('article')->where($where)->find();
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }


    /**
     * 基本信息修改
     * @return \think\response\Json|void
     */
    public function bannerDetail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        $where['id'] = $id;
        $r=db('banner')->where($where)->find();
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    public function serveSubscribeList(){
        $list=db('server_cate_subscribe')->where(['is_delete'=>0])->order('sort desc')->select();
        foreach ($list as &$v){
            $v['child'] = db('server_subscribe')->where(['cate_id'=>$v['id'],'is_delete'=>0,'status'=>0])->select();
        }
        return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
    }

    public function visitingCard(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
        if($id){
            $data=db('technician')->where(['id'=>$id,'status'=>0,'is_delete'=>0])->find();
            if($data){
                $data['store_detail']=db('store')->where(['id'=>$data['store_id'],'status'=>0,'is_delete'=>0])->find();
                $data['config']=db('config')->where(['id'=>1])->find();
            }
            return json(['code' => 1, 'msg' => '操作成功','data'=>$data]);
        }
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $data=db('technician')->where(['mobile'=>$isLogin['mobile'],'status'=>0,'is_delete'=>0])->find();
        if($data){
            $data['store_detail']=db('store')->where(['id'=>$data['store_id'],'status'=>0,'is_delete'=>0])->find();
            $data['config']=db('config')->where(['id'=>1])->find();
        }
        return json(['code' => 1, 'msg' => '操作成功','data'=>$data]);
    }

    public function saveVisitingCard(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        $position = isset($post['position']) && $post['position'] != '' ? $post['position'] : 0;
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $r=db('technician')->where(['mobile'=>$isLogin['mobile'],'status'=>0,'is_delete'=>0])->find();
        if(!$r){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $r=db('technician')->where(['id'=>$r['id']])->update(['position'=>$position,'update_time'=>time()]);
        if(!$r){
            return json(array('code' => '0', 'msg' => '更新失败'));
        }
        return json(array('code' => '1', 'msg' => '更新成功'));
    }


    public function getOrderImgList(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $list=db('user_order_img')->where(['order_id'=>$order_id])->select();
        $afterList=array();$ingList=array();$beforeList=array();
        foreach ($list as &$v){
            if($v['type'] == 1){
                $afterList[]=$v;
            }else if($v['type'] == 2){
                $ingList[]=$v;
            }else if($v['type'] == 3){
                $beforeList[] = $v;
            }
        }
        return json(array('code' => '1', 'msg' => '更新成功','afterList'=>$afterList,'ingList'=>$ingList,'beforeList'=>$beforeList));
    }

    public function delOrderImage(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
        $oRes=db('user_order_img')->where(['id'=>$id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '信息错误']);
        }
        $r=db('user_order_img')->where(['id'=>$id])->delete();
        if(!$r){
            return json(array('code' => '0', 'msg' => '操作失败'));
        }
        return json(array('code' => '1', 'msg' => '更新成功'));
    }

    public function changeOrderImage(){
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] != '' ? $post['openid'] : 0;
        if(!$openid){
            return json(array('code' => '0', 'msg' => '用户信息错误'));
        }
        $isLogin=$this->isLogin($openid);
        if($isLogin === false){
            return json(['code'=>-1,'msg'=>'未登录请先登录']);
        }
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $r=db('user_order')->where(['id'=>$order_id])->update(['status'=>4]);
        if(!$r){
            return json(array('code' => '0', 'msg' => '操作失败'));
        }
        return json(array('code' => '1', 'msg' => '更新成功'));
    }

}




